package com.zcy.service.impl;

import com.zcy.annotation.HessianService;
import com.zcy.dynamic.DynamicCompileEngine;
import com.zcy.service.IGroupService;
import org.hibernate.Session;
import org.hibernate.internal.SessionFactoryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.*;
import java.util.Map;

/**
 * Created by join on 2017/6/21.
 */
@HessianService("/groupapi")
@Service
@Transactional
public class GroupServiceImpl implements IGroupService {

    @PersistenceContext
    private EntityManager em;

    @Autowired
    private DynamicCompileEngine dynamicEngine;

    @Transactional
    public String test(String msg) {


        Session session = em.unwrap(Session.class);
        SessionFactoryImpl sessionFactory = (SessionFactoryImpl)session.getSessionFactory();
        try {
            sessionFactory.doLoadMetaData(new FileInputStream(new File("/Users/join/Desktop/dy.hbm.xml")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            String fullName = "com.zcy.service.impl.SysModfService";
            StringBuilder src = new StringBuilder();

            File file = ResourceUtils.getFile("classpath:DyServiceTemplate.tpl");
            InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file), "UTF-8");//考虑到编码格式
            BufferedReader bufferedReader = new BufferedReader(read);

            String lineTxt = null;
            while ((lineTxt = bufferedReader.readLine()) != null) {
                src.append(lineTxt);
            }
            read.close();
            System.out.println(src);
            DynamicCompileEngine de = DynamicCompileEngine.getInstance();
            String beanName = de.compileToSpringBeanAndRegistService(fullName, src.toString(), null);
            System.out.println("##########" + msg);
        }catch (Exception e){
            e.printStackTrace();
        }
        return " 政务产品组欢迎您。。。";
    }

    @Override
    @Transactional
    public String save(String entityName, Map<String, Object> entity) {

        Session session = em.unwrap(Session.class);
        session.save(entityName,entity);


        return "保存成功";
    }


}
